/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.rpc.isfd.oauth;

import com.comac.ins.isfd.rpc.isfd.config.IsfdRequestConfig;
import com.comac.ins.isfd.rpc.isfd.constants.IsfdConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class IsfdOauthInterceptor implements ClientHttpRequestInterceptor {

    @Autowired
    private IsfdRequestConfig isfdRequestConfig;

    @Autowired
    private IsfdOauthTokenUtils isfdOauthTokenUtils;

    private String getOAuthToken() {
        return isfdOauthTokenUtils.getCurrentToken(isfdRequestConfig, Boolean.TRUE);
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        String uriPath = request.getURI().getPath();
        if (!isfdRequestConfig.getExcludedUris().contains(uriPath)) {
            request.getHeaders().set(IsfdConstants.AUTHORIZATION, IsfdConstants.BEARER + getOAuthToken());
        }
        return execution.execute(request, body);
    }
}
